package maple.core;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.IOException;
import java.util.logging.Level;

import jade.lang.acl.ACLMessage;
import jade.wrapper.StaleProxyException;

import maple.lang.Command;
import maple.lang.Language;

public class Tester extends MapleAgent
{
	private BufferedReader _reader;

	public Tester()
	{
		super();

		_reader = new BufferedReader( new InputStreamReader( System.in ) );
	}

	protected void takeDown()
	{
		try
		{
			if( _reader != null )
			{
				_reader.close();
			}
		}
		catch( IOException e )
		{
			_logger.log( Level.WARNING, "", e );
		}

		try
		{
			getContainerController().kill();
		}
		catch( StaleProxyException e )
		{
			_logger.log( Level.WARNING, "", e );
		}
	}

	protected void actionInform( final ACLMessage message )
	{
		System.out.println( message.getContent() );
	}

	protected boolean distribute()
	{
		try
		{
			String content = _reader.readLine();
			if( !content.equals( "exit" ) )
			{
				if( !content.equals( "" ) )
				{

					int index = content.indexOf( Language.DELIMITER );
					if( index > 0 )
					{
						String receiver = content.substring( 0, index );
						Command command = new Command( content.substring( index + 1 ) );
						if( command.isAvailable() )
						{
							String[] tokens = getName().split( Language.AT );
							if( sendMessage( ACLMessage.REQUEST, receiver, command.toString(), null, "Printer" + Language.AT + tokens[ 1 ] ) )
							{
								// wait for a response
								ACLMessage message = blockingReceive();
								switch( message.getPerformative() )
								{
									case ACLMessage.INFORM:
										actionInform( message );
										break;
								}
							}
							else
							{
								System.out.println( Command.Message.BAD_COMMAND.toString() );
							}
						}
						else
						{
							System.out.println( Command.Message.BAD_COMMAND.toString() );
						}
					}
					else
					{
						System.out.println( Command.Message.BAD_COMMAND.toString() );
					}
				}
			}
			else
			{
				doDelete();
			}
		}
		catch( IOException e )
		{
			_logger.log( Level.WARNING, "", e );
		}
		return true;
	}
}
